package controllers;

import java.util.ArrayList;
import java.util.List;

import models.AppUser;
import models.Question;
import play.mvc.Controller;
import play.mvc.With;

import com.google.gson.Gson;

import controllers.gcm.GCMSender;

@With(Secure.class)
public class Application extends Controller {

    public static void index() {
        List<Question> questions = Question.findAll();
        render(questions);
    }

    public static void saveQuestion(long questionid, String formquestion, String formanswer, String formwrong1,
            String formwrong2, String formtag) {
        Question question = Question.findById(questionid);
        question.question = formquestion;
        question.rightAnswer = formanswer;
        question.wrongAnswer1 = formwrong1;
        question.wrongAnswer2 = formwrong2;
        question.tag = formtag;
        question.save();
        index();
    }

    public static void deleteQuestion(long questionid) {
        Question question = Question.findById(questionid);
        question.delete();
        index();
    }

    public static void editQuestion(long questionid) {
        Question question = Question.findById(questionid);
        render(question);
    }

    public static void addQuestion() {
        Question question = new Question("", "", "", "", "");
        question.save();
        editQuestion(question.id);
    }

    public static void send2Mobile(long questionID) {
        Question question = Question.findById(questionID);
        Gson gson = new Gson();
        String message = gson.toJson(question);
        GCMSender gcmSender = new GCMSender();
        ArrayList<String> mobileIds = new ArrayList<String>();
        List<AppUser> appUsers = AppUser.findAll();
        for (AppUser appUser : appUsers) {
            mobileIds.add(appUser.mobileID);
        }
        gcmSender.sendMessage(mobileIds, message);
        index();
    }

}